package com.fumin.service;

import com.fumin.common.RequestHolder;
import com.fumin.dao.SysRoleAclMapper;
import com.fumin.model.SysRoleAcl;
import com.fumin.util.IpUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * 角色权限service
 * @Author xiayuxuanmin
 * @Date 2019/11/19
 * @Description
 */
@Service
public class SysRoleAclService {
    @Resource
    private SysRoleAclMapper sysRoleAclMapper;
    @Resource
    private SysLogService sysLogService;

    /**
     * 更新指定角色的权限点
     * @param roleId 角色ID
     * @param aclIdList 权限ID集合
     */
    public void changeRoleAcls(Integer roleId, List<Integer> aclIdList){
        //获取当前角色原来已经拥有的权限点ID集合
        List<Integer> originAclIdList = sysRoleAclMapper.getAclIdListByRoleIdList(Lists.newArrayList(roleId));
        //判断原来的权限点和现在的权限点是否完全一致,如果一致,表示权限没有变化,不用处理
        if(originAclIdList.size() == aclIdList.size()){
            HashSet<Integer> originAclIdSet = Sets.newHashSet(originAclIdList);
            HashSet<Integer> aclIdSet = Sets.newHashSet(aclIdList);
            originAclIdSet.removeAll(aclIdList);
            if (CollectionUtils.isEmpty(originAclIdSet)) {
                //表示权限没有发生改变
                return;
            }
        }
        this.udpateRoleAcls(roleId,aclIdList);
        sysLogService.saveRoleAclLog(roleId,originAclIdList,aclIdList);
    }

    /**
     * 重新设置角色拥有的权限
     * 为了保持全部成功,或者失败,这里加入事务
     * @param roleId 角色ID
     * @param aclIdList 权限点ID集合
     */
    @Transactional
    public void udpateRoleAcls(int roleId,List<Integer> aclIdList){
        //清除原有权限
        sysRoleAclMapper.deleteByRoleId(roleId);
        List<SysRoleAcl> roleAclList = Lists.newArrayList();
        for (Integer aclId : aclIdList) {
            SysRoleAcl roleAcl = SysRoleAcl.builder().roleId(roleId).aclId(aclId)
                    .operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()))
                    .operateTime(new Date()).build();
            roleAclList.add(roleAcl);
        }
        //新增新的权限
        sysRoleAclMapper.batchInsert(roleAclList);
    }
}
